Git Memorandum

观书有会意处,题其衣裳,以记其事~

1、拉取远程分支并创建本地分支

1
$ git checkout -b branch_x origin/branch_x

使用该方式会在本地新建分支branch_x,并自动切换到该本地分支branch_x

2、 将本地分支与远程分支关联

1
$ git branch --set-upstream-to=origin/<branch> master

设置本地分支master跟踪origin/远程分支

3、Push本地代码到远程新分支

1
$ git push origin 本地分支:远端希望创建的分支

使用场景:比如在本地新建一个分支进行了部分修改,希望能够将这些修改push到远程并新建一个新分支

4、本地分支重命名

1
$ git branch -m oldName newName

5、一个项目对应多个远程仓库

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
$ git remote
github

$ git remote -v
github https://github.com/min/test.git (fetch)
github https://github.com/min/test.git (push)

$ git remote add gitlab https://gitlab-min.com/min/test.git

$ git remote
github
gitlab

$ git remote -v
github https://github.com/min/test.git (fetch)
github https://github.com/min/test.git (push)
gitlab https://gitlab-min.com/min/test.git (fetch)
gitlab https://gitlab-min.com/min/test.git (push)

使用场景:比如我创建了一个OpenCV Repo,添加了一些自己的修改,并使用Gitlab进行管理,但是又希望可以及时同步Github最新的commit到Gitlab上,所以好的方式就是有两个remote,然后本地有两个分支分别对应gitlab和github,如果有新的commit,我就可以使用cherry-pick/merge命令同步到gitlab上,

6、git rebase/git merge

现在我们有这样的两个分支,origin和mywork,提交如下:

git-origin

在my work执行git merge origin,然后会得到如下结果:

git-origin

在my work执行git rebase origin,然后得到如下结果:

git-origin

可以看到,merge操作会生成一个新的节点,之前的提交分开显示。而rebase操作不会生成新的节点,是将两个分支融合成一个线性的提交。

不要在公共分支上使用!!!

如果你想要一个干净的,没有merge commit的线性历史树,那么你应该选择git rebase, 如果你想保留完整的历史记录,并且想要避免重写commit history的风险,你应该选择使用git merge

7、更新远程分支列表

1
git remote update origin --prune